<template>
	<div class="wrapper">

		<!-- header部分 -->
		<header>
			<BackButton></BackButton>
			<p>在线支付</p>
		</header>

		<!-- 订单信息部分 -->
		<h3>订单信息：</h3>
		<div class="order-info">
			<p>
				{{orders.business.businessName}}
				<i class="fa fa-caret-down" @click="detailetShow"></i>
			</p>
			<p>&#165;{{orders.orderTotal}}</p>
		</div>

		<!-- 订单明细部分 -->
		<ul class="order-detailet" v-show="isShowDetailet">
			<li v-for="item in orders.list">
				<p>{{item.food.foodName}} x {{item.quantity}}</p>
				<p>&#165;{{(item.food.foodPrice*item.quantity).toFixed(2)}}</p>
			</li>
			<li>
				<p>配送费</p>
				<p>&#165;{{orders.business.deliveryPrice}}</p>
			</li>
		</ul>

		<!-- 积分抵扣部分 - 添加在支付方式上方 -->
		<div class="points-section">
  <div class="points-header">
    <label class="checkbox-container">
      <input type="checkbox" v-model="usePoints">
      <span class="checkmark"></span>
      <span>使用积分抵扣</span>
    </label>
    <span class="points-balance">可用积分: {{pointsBalance}}</span>
  </div>
  
  <div class="points-input-area" v-if="usePoints">
    <div class="input-wrapper">
      <input 
        type="number" 
        v-model="pointsToUse"
        :max="pointsBalance" 
        placeholder="请输入要抵扣的积分"
      />
      <button @click="useMaxPoints">全部使用</button>
    </div>
    <div class="points-info">
      <p>可抵扣金额: ¥{{getPointsDeduction().toFixed(2)}}</p>
      <p>实付金额: ¥{{getFinalPayment().toFixed(2)}}</p>
    </div>
  </div>
</div>

		<!-- 现有的支付方式部分 -->
		<ul class="payment-type">
				<li @click="selectPayment('alipay')" :class="{active: paymentMethod === 'alipay'}">
					<img src="../assets/alipay.png">
					<i class="fa fa-check-circle" v-if="paymentMethod === 'alipay'"></i>
				</li>
				<li @click="selectPayment('wechat')" :class="{active: paymentMethod === 'wechat'}">
					<img src="../assets/wechat.png">
					<i class="fa fa-check-circle" v-if="paymentMethod === 'wechat'"></i>
				</li>
				<li @click="selectPayment('wallet')" :class="{active: paymentMethod === 'wallet'}">
					<div class="wallet-payment">
						<i class="fa fa-wallet"></i>
						<span>钱包支付</span>
						<span class="wallet-balance">余额: ¥{{walletBalance.toFixed(2)}}</span>
					</div>
					<i class="fa fa-check-circle" v-if="paymentMethod === 'wallet'"></i>
				</li>
		</ul>
		<div class="payment-button">
			<button style="font-size: 5vw" @click="aleadyPay">确认支付</button>
		</div>

		<!-- 底部菜单部分 -->
		<Footer></Footer>
	</div>
</template>

<script>
	import Footer from '../components/Footer.vue';
	import BackButton from '../components/BackButton.vue';
	export default {
		name: 'Payment',
		data(){
			return {
				// 已有的数据
				orderId: this.$route.query.orderId,
				routerType: this.$route.query.routerType,
				orders: {
					business: {}
				},
				isShowDetailet: false,
				paymentMethod: 'alipay',
				walletBalance: 0,
				walletId: null,
				user: {},
				
				// 积分相关数据
				pointsBalance: 0,  // 积分余额，暂时写死
				pointsToUse: 0,       // 用户输入的积分
				usePoints: false      // 是否使用积分抵扣
			}
		},
		created() {
			// 获取订单信息
			this.$axios.get('http://localhost:14000/OrdersController/Orders', {
				params: {
					orderId: this.orderId
				}
			}).then(response => {
				this.orders = response.data.result;
			}).catch(error => {
				console.error(error);
			});
			
			// 获取用户信息
			this.user = this.$getSessionStorage('user');
			
			 // 如果用户已登录，获取钱包信息
			if(this.user && this.user.userId) {
				this.getWalletInfo();
				this.getPointsBalance(); // 获取积分余额
			}
		},
		mounted() {
			//这里的代码是实现：一旦路由到在线支付组件，就不能回到订单确认组件。
			//先将当前url添加到history对象中
			//history.pushState(null,null,document.URL);
			//popstate事件能够监听history对象的变化
			window.onpopstate = () => {
				//this.$router.push({path:'/index'});
			}
		},
		destroyed() {
			window.onpopstate = null;
		},
		methods: {
			detailetShow(){
				this.isShowDetailet = !this.isShowDetailet;
			},
			selectPayment(method) {
				this.paymentMethod = method;
			},
			// 获取钱包信息
			getWalletInfo() {
				// 从UserController获取walletId
				this.$axios.get(`http://localhost:14000/UserController/walletId`, {
					params: {
						userId: this.user.userId
					}
				})
				.then(response => {
					if(response.data && response.data.result) {
						this.walletId = response.data.result;
						// 获取到walletId后，再获取余额
						this.getWalletBalance();
					}
				}).catch(error => {
					console.error("获取钱包信息失败:", error);
				});
			},
			
			// 修改为使用walletId获取余额
			getWalletBalance() {
				if(!this.walletId) return;
				
				this.$axios.get(`http://localhost:14000/VirtualWalletController/${this.walletId}`)
					.then(response => {
						if(response.data && response.data.result) {
							this.walletBalance = response.data.result.balance;
						}
					}).catch(error => {
						console.error("获取钱包余额失败:", error);
					});
			},
			// 获取积分余额
getPointsBalance() {
    // 确保用户已登录
    if (!this.user || !this.user.userId) {
        console.warn("未登录用户无法获取积分");
        return;
    }
    
    // 调用积分查询接口
    this.$axios.get(`http://localhost:14000/UserController/UserPoints`, {
        params: {
            userId: this.user.userId
        }
    })
    .then(response => {
        if (response.data && response.data.code === 200) {
            this.pointsBalance = response.data.result;
            console.log("获取到用户积分:", this.pointsBalance);
        } else {
            console.warn("获取积分失败:", response.data);
            // 保留默认积分值作为后备
        }
    })
    .catch(error => {
        console.error("获取积分余额失败:", error);
        // 获取失败时保留默认积分值
    });
},

			// 使用最大可用积分
			// 使用最大可用积分
			useMaxPoints() {
				// 计算所需积分（10000积分=1元）
				const requiredPoints = this.orders.orderTotal * 10000;
				// 使用可用积分和所需积分中的较小值
				this.pointsToUse = Math.min(this.pointsBalance, requiredPoints);
			},
			
			// 计算积分可抵扣金额
			getPointsDeduction() {
				if (!this.usePoints || this.pointsToUse <= 0) return 0;
				return this.pointsToUse / 10000; // 假设100积分=1元
			},
			
			// 计算最终支付金额
			getFinalPayment() {
				const deduction = this.getPointsDeduction();
				const finalAmount = this.orders.orderTotal - deduction;
				return finalAmount > 0 ? finalAmount : 0;
			},
			
			// 修改支付方法
			aleadyPay() {
				console.log("订单编号：", this.orderId);
				console.log("支付方式：", this.paymentMethod);
				
				// 定义基本请求参数
				let requestParams = {
					orderId: this.orderId
				};
				
				// 添加积分信息（如果使用了积分）
				if (this.usePoints && this.pointsToUse > 0) {
					requestParams.usePoints = true;
					requestParams.pointsUsed = this.pointsToUse;
					requestParams.pointsDeduction = this.getPointsDeduction(); // 添加明确的抵扣金额
				}
				
				// 获取最终支付金额
				const finalPaymentAmount = this.getFinalPayment();
				
				// 如果选择的是钱包支付
				if (this.paymentMethod === 'wallet') {
					// 检查钱包余额是否足够支付最终金额
					if (this.walletBalance < finalPaymentAmount) {
						alert("钱包余额不足，请充值或选择其他支付方式");
						return;
					}
					
					// 设置为钱包支付
					requestParams.orderType = 2;
					requestParams.fromWalletId = this.walletId;
					requestParams.amount = finalPaymentAmount; // 使用积分抵扣后的金额
                    
					// 获取商家钱包ID
					this.getBusinessWalletId(this.orders.business.businessId)
						.then(toWalletId => {
							if (!toWalletId) {
								alert("商家尚未开通钱包支付功能，请选择其他支付方式");
								return;
							}
							
							requestParams.toWalletId = toWalletId;
							this.completeOrder(requestParams);
						})
						.catch(error => {
							console.error("获取商家钱包ID失败:", error);
							alert("支付失败，请稍后再试或选择其他支付方式");
						});
				} else {
					// 支付宝或微信支付
					requestParams.orderType = 1;
					requestParams.amount = finalPaymentAmount; // 使用积分抵扣后的金额
					
					// 获取商家钱包ID
					this.getBusinessWalletId(this.orders.business.businessId)
						.then(toWalletId => {
							if (!toWalletId) {
								alert("商家钱包信息获取失败，请稍后再试");
								return;
							}
							
							requestParams.toWalletId = toWalletId;
							this.completeOrder(requestParams);
						})
						.catch(error => {
							console.error("获取商家钱包ID失败:", error);
							alert("支付失败，请稍后再试");
						});
				}
			},
			
			// 获取商家钱包ID
			getBusinessWalletId(businessId) {
				return new Promise((resolve, reject) => {
					this.$axios.get(`http://localhost:14000/UserController/walletIdByBusiness`, {
						params: {
							businessId: businessId
						}
					})
					.then(response => {
						if (response.data && response.data.code === 200 && response.data.result) {
							resolve(response.data.result);
						} else {
							console.warn("商家钱包信息获取失败:", response.data);
							resolve(null);
						}
					})
					.catch(error => {
						console.error("获取商家钱包ID出错:", error);
						reject(error);
					});
				});
			},
			
			// 完成订单处理
			completeOrder(params) {
				console.log("发送的支付参数:", params); // 添加日志
				this.$axios.put('http://localhost:14000/OrdersController/Orders', null, {
					params: params
				})
				.then(response => {
					if (response.data.code === 200) {
						// 支付成功后，如果使用了积分，则调用积分扣除API
						if (this.usePoints && this.pointsToUse > 0) {
							// 创建积分日志对象
							const pointLog = {
								userId: this.user.userId,
								change: -this.pointsToUse, // 负数表示扣除
								reason: "积分抵扣"
							};
							
							// 调用积分记录API
							this.$axios.post('http://localhost:14000/PointController/insertLog', pointLog)
								.then(pointResponse => {
									console.log("积分扣除成功:", pointResponse.data);
								})
								.catch(error => {
									console.error("积分扣除失败:", error);
									// 这里不影响主流程，所以即使失败也继续后续操作
								});
						}
						
						alert("支付成功");
						if (this.routerType) {
							this.$router.go(-1);
						} else {
							this.$router.go(-2);
						}
					} else {
						alert(response.data.result ? response.data.result.join('\n') : "支付失败");
					}
				}).catch(error => {
					if (error.response && error.response.data && error.response.data.result) {
						// 显示具体错误信息
						alert(error.response.data.result.join('\n'));
					} else {
						alert("订单处理失败，请稍后再试");
					}
					console.error("支付失败:", error);
				});
			}
		},
		components: {
			Footer,BackButton
		}
	}
</script>

<style scoped>
	/****************** 总容器 ******************/
	.wrapper {
		width: 100%;
		height: 100%;
	}

	/****************** header部分 ******************/
	.wrapper header {
		width: 100%;
		height: 12vw;
		background-color: #0097FF;
		color: #fff;
		font-size: 4.8vw;

		position: fixed;
		left: 0;
		top: 0;
		z-index: 1000;

		display: flex;
		justify-content: center;
		align-items: center;
	}

	/****************** 订单信息部分 ******************/
	.wrapper h3 {
		margin-top: 12vw;
		box-sizing: border-box;
		padding: 4vw 4vw 0;

		font-size: 4vw;
		font-weight: 300;
		color: #999;
	}

	.wrapper .order-info {
		box-sizing: border-box;
		padding: 4vw;
		font-size: 4vw;
		color: #666;

		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.wrapper .order-info p:last-child {
		color: orangered;
	}

	/****************** 订单明细部分 ******************/
	.wrapper .order-detailet {
		width: 100%;
	}

	.wrapper .order-detailet li {
		width: 100%;
		box-sizing: border-box;
		padding: 1vw 4vw;

		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.wrapper .order-detailet li p {
		font-size: 3vw;
		color: #666;
	}

	/****************** 支付方式部分 ******************/
	.wrapper .payment-type {
		width: 100%;
	}

	.wrapper .payment-type li {
		width: 100%;
		box-sizing: border-box;
		padding: 4vw;

		display: flex;
		justify-content: space-between;
		align-items: center;
		cursor: pointer;
	}

	.wrapper .payment-type li img {
		width: 33vw;
		height: 8.9vw;
	}

	.wrapper .payment-type li .fa-check-circle {
		font-size: 5vw;
		color: #38CA73;
	}

	.wrapper .payment-type li.active {
		background-color: #f0f0f0;
	}

	.wrapper .wallet-payment {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
	}

	.wrapper .wallet-payment .fa-wallet {
		font-size: 5vw;
		color: #666;
	}

	.wrapper .wallet-payment span {
		font-size: 3vw;
		color: #666;
	}

	.wrapper .wallet-payment .wallet-balance {
		color: #38CA73;
	}

	.wrapper .payment-button {
		width: 100%;
		box-sizing: border-box;
		padding: 4vw;
	}

	.wrapper .payment-button button {
		width: 100%;
		height: 10vw;
		border: none;
		/*去掉外轮廓线*/
		outline: none;
		border-radius: 4px;
		background-color: #38CA73;
		color: #fff;
	}

	/****************** 积分抵扣相关样式 ******************/
.points-section {
  width: 100%;
  box-sizing: border-box;
  padding: 4vw;
  background-color: #f9f9f9;
  border-radius: 4px;
  margin-bottom: 4vw;
}

.points-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 3vw;
}

.checkbox-container {
  display: flex;
  align-items: center;
  font-size: 4vw;
  color: #333;
  cursor: pointer;
  position: relative; /* 添加相对定位 */
}

/* 隐藏原生checkbox */
.checkbox-container input[type="checkbox"] {
  position: absolute;
  opacity: 0;
  cursor: pointer;
  height: 0;
  width: 0;
}

.checkmark {
  width: 4vw;
  height: 4vw;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 2px;
  margin-right: 2vw;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 当checkbox被选中时，显示自定义对勾 */
input[type="checkbox"]:checked + .checkmark:after {
  content: '✓';
  color: #38CA73;
}

.points-balance {
  font-size: 3.2vw;
  color: #FF6600;
}

.points-input-area {
  padding-top: 2vw;
  border-top: 1px solid #eee;
}

.input-wrapper {
  display: flex;
  margin-bottom: 3vw;
}

.input-wrapper input {
  flex: 1;
  height: 8vw;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 0 2vw;
  font-size: 3.5vw;
}

.input-wrapper button {
  width: 20vw;
  height: 8vw;
  margin-left: 2vw;
  border: none;
  border-radius: 4px;
  background-color: #38CA73;
  color: white;
  font-size: 3.2vw;
}

.points-info {
  display: flex;
  justify-content: space-between;
}

.points-info p {
  font-size: 3.2vw;
  color: #666;
}

.points-info p:last-child {
  color: #FF6600;
  font-weight: bold;
}
</style>
